package com.tuling.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//传统的jdbc
public class DBUtils {
    //加载配置文件
    private static Properties properties = new Properties();
    //写一个代码块
    static{
        try {
            InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
            properties.load(is);
            //加载数据驱动
            Class.forName(properties.getProperty("driver"));
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    //获取数据库链接
    public static Connection getConnection() {
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        try {
            Connection connection = DriverManager.getConnection(url, username, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    //关闭相关资源
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs){

        try{
            if(rs!=null){
                rs.close();
            }
            if(stmt!=null){
                stmt.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
